//
//  ALTAnisetteData+Sanitize.m
//  XAuthServer
//
//  Created by 吴双 on 2023/1/22.
//

#import "ALTAnisetteData+Sanitize.h"

@implementation ALTAnisetteData (Sanitize)

- (void)sanitize {
    [self sanitizeByBundleID:@"com.apple.dt.Xcode" version:@"3594.4.19"];
}

- (void)sanitizeByBundleID:(NSString *)bundleID version:(NSString *)version {
    NSString *deviceDescription = self.deviceDescription;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"\\(com\\.apple\\..*/[0-9\\.]*\\)" options:kNilOptions error:nil];
    NSRange range = [regular firstMatchInString:deviceDescription options:kNilOptions range:NSMakeRange(0, deviceDescription.length)].range;
    NSString *replace = [NSString stringWithFormat:@"(%@/%@)", bundleID, version];
    NSString *result = [deviceDescription stringByReplacingCharactersInRange:range withString:replace];
    self.deviceDescription = result;
    return;
}

- (instancetype)initWithOriginKeyedJSON:(NSDictionary *)json {
    NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
    return [self initWithMachineID:json[@"X-Apple-I-MD-M"]
                   oneTimePassword:json[@"X-Apple-I-MD"]
                       localUserID:json[@"X-Apple-I-MD-LU"]
                       routingInfo:[(NSString *)json[@"X-Apple-I-MD-RINFO"] integerValue]
            deviceUniqueIdentifier:json[@"X-Mme-Device-Id"]
                deviceSerialNumber:json[@"X-Apple-I-SRL-NO"]
                 deviceDescription:json[@"X-MMe-Client-Info"]
                              date:[formatter dateFromString:json[@"X-Apple-I-Client-Time"]]
                            locale:[NSLocale localeWithLocaleIdentifier:json[@"X-Apple-Locale"]]
                          timeZone:[NSTimeZone timeZoneWithName:json[@"X-Apple-I-TimeZone"]]];
}

- (NSDictionary *)originKeyedJSON {
    NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
    NSMutableDictionary *json = [NSMutableDictionary dictionary];
    json[@"X-Apple-I-MD-M"] = self.machineID;
    json[@"X-Apple-I-MD"] = self.oneTimePassword;
    json[@"X-Apple-I-MD-LU"] = self.localUserID;
    json[@"X-Apple-I-MD-RINFO"] = @(self.routingInfo).stringValue;
    json[@"X-Mme-Device-Id"] = self.deviceUniqueIdentifier;
    json[@"X-Apple-I-SRL-NO"] = self.deviceSerialNumber;
    json[@"X-MMe-Client-Info"] = self.deviceDescription;
    json[@"X-Apple-I-Client-Time"] = [formatter stringFromDate:self.date];
    json[@"X-Apple-Locale"] = self.locale.localeIdentifier;
    json[@"X-Apple-I-TimeZone"] = self.timeZone.name;
    return json;
}

@end
